package com.base.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.base.dao.DictItemDao;
import com.base.entity.DictItemEntity;
import com.base.entity.SysUserEntity;
import com.base.service.DictItemService;
import com.base.utils.PageUtils;
import com.base.utils.Query;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * @author Amadeus
 */
@Service("dictItemService")
public class DictItemServiceImpl extends ServiceImpl<DictItemDao, DictItemEntity> implements DictItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<DictItemEntity> page = this.page(
                new Query<DictItemEntity>().getPage(params),
                new QueryWrapper<DictItemEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveDictItem(DictItemEntity dictItem) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        dictItem.setCreateBy(user.getUsername());
        this.save(dictItem);
    }

    @Override
    public void saveOrUpdateDictItem(DictItemEntity dictItem) {
        SysUserEntity user = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        dictItem.setUpdateBy(user.getUsername());
        this.saveOrUpdate(dictItem);
    }


    @Override
    public PageUtils getDictItemList(Map<String, Object> params) {
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String dictId = (String) params.get("dictId");
        IPage<DictItemEntity> page = this.page(
                new Query<DictItemEntity>().getPage(params),
                Wrappers.<DictItemEntity>lambdaQuery()
                        .eq(DictItemEntity::getDictId, dictId)
                        .eq(StrUtil.isNotBlank(status), DictItemEntity::getStatus, status)
                        .and(StrUtil.isNotBlank(key), i -> i
                                .like(StrUtil.isNotBlank(key), DictItemEntity::getItemText, key)
                                .or().like(StrUtil.isNotBlank(key), DictItemEntity::getItemValue, key))
        );

        return new PageUtils(page);
    }

}